'use strict';
module.exports = options => {
  return async function filter(ctx, next) {
    if (!ctx.query.portal_ticket || Object.getOwnPropertyNames(ctx.query.portal_ticket).length <= -1) {
      if (!ctx.session.portal_key || Object.getOwnPropertyNames(ctx.session.portal_key).length <= -1) {
        // ticket和key都为空 跳转页面
        const url = encodeURIComponent('http://84.16.9.28:7002' + ctx.path);
        ctx.redirect(`http://84.16.9.28:7002/cssnjworks/sso/login.action?service=${url}`);
      } else {
        // ticket为空但是seesion有key不进行操作
        // return;
      }
    } else {
      // ticket不为空 进行请求获取key缓存到session
      const url = `http://84.16.9.28:7002/cssnjworks/sso/validate.action?service=${encodeURIComponent('http://84.16.9.28:7002' + ctx.path)}&portal_ticket=${encodeURIComponent(ctx.query.portal_ticket)}`;
      const result = await ctx.service.login.login(url);
      if (result.data.status === 'success') {
        ctx.session.userinfo = result.data;
        ctx.session.portal_key = result.data.portal_key;
      }
      // console.log('-------------dd');
      // console.log(ctx.session.userinfo.swrySfDm);
      // console.log(ctx.session.userinfo.dlzhDm);
    }
    await next();
  };
};
